package com.atguigu.atcrowdfunding.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.atguigu.atcrowdfunding.bean.TMenu;
import com.atguigu.atcrowdfunding.mapper.TMenuMapper;
import com.atguigu.atcrowdfunding.service.TMenuService;

@Service
public class TMenuServiceImpl implements TMenuService {
	
	Logger log = LoggerFactory.getLogger(this.getClass());

	@Autowired
	TMenuMapper menuMapper;

	@Override
	public List<TMenu> listAllMenu() {
//		只放父菜单
		List<TMenu> menuList = new ArrayList<TMenu>();
//		所有菜单
		List<TMenu> allMenuList = menuMapper.selectByExample(null);
		Map<Integer,TMenu> cache = new HashMap<Integer,TMenu>();
		for (TMenu tMenu : allMenuList) {
			if(tMenu.getPid() == 0) {
//				将所有父菜单装载
				menuList.add(tMenu);
				cache.put(tMenu.getId(), tMenu);
			}
		}
		
		for (TMenu tMenu : allMenuList) {
			if(tMenu.getPid() != 0) {
//				将所有子菜单装载,通过子菜单pid查找父菜单
				TMenu parent = cache.get(tMenu.getPid());
//				将父菜单的children集合中添加该子菜单
				parent.getChildren().add(tMenu);
			}
		}
		log.debug("菜单={}",menuList);
		return menuList;
	}

	@Override
	public List<TMenu> listAllMenuOnTree() {
		return menuMapper.selectByExample(null);
	}

	@Override
	@Transactional
	public void saveMenu(TMenu menu) {
		menuMapper.insertSelective(menu);
	}

	@Override
	public TMenu getMenuById(Integer id) {
		return menuMapper.selectByPrimaryKey(id);
	}

	@Override
	@Transactional
	public void updateMenu(TMenu menu) {
		menuMapper.updateByPrimaryKeySelective(menu);
	}

	@Override
	@Transactional
	public void deleteMenu(Integer id) {
		menuMapper.deleteByPrimaryKey(id);
	}
	
}
